package com.train.JUC;

import java.util.concurrent.CopyOnWriteArrayList;
/**
 * {@link CopyOnWriteArrayList}是线程安全的一个集合
 * */
public class TicketsSales implements Runnable{
    //票数量
    private CopyOnWriteArrayList<Ticket> tickets = new CopyOnWriteArrayList<>();
    public TicketsSales(Integer ticketsNums ){
        // 初始化tickets，假设每排20座位
        for (Integer i = 1; i <= ticketsNums; i++) {
            tickets.add(new Ticket(
                    String.format("%5s",i).replace(' ','0'),
                    (i/20+1)+"排"+(i%20)+"座",
                    228.9
            ));
        }
    }
    @Override
    public void run() {
        try {
            buyTicket();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 第一种方法，对方法加同步锁
     * */
    private synchronized void buyTicket() throws InterruptedException {
        if ( tickets.size() >= 1){
            String threadName = Thread.currentThread().getName();
            Integer index = tickets.size() - 1;
            Ticket ticket = tickets.get(index);
            tickets.remove(ticket);
            System.out.println(String.format("%s购买票 票号：%s 座位：%s 票价：%.2f ￥",threadName,ticket.getNo(),ticket.getSeat(),ticket.getPrice()));
            //买完一张表，将CPU执行权礼让给其他线程，但自身还是会进入下一次CPU的抢夺
            Thread.currentThread().yield();
        }
    }
}
